/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities;

import java.io.Serializable;
import java.util.*;
import metadata.SystemMetaData;
import org.jgap.IChromosome;

/**
 * This class represents a mapping from the domain of all views (not variants),
 * to the domain of BitSet chromozomes containing BitSet genes.
 * @author Dragan Sahpaski
 */
public class Domain implements Serializable {

    private ViewGraph viewGraph;
    private SystemMetaData systemMetaData;
    private List<Atribute> allAtributes;
    private HashMap<Integer, Table> materializedViews;

    public Domain(ViewGraph viewGraph, SystemMetaData systemMetaData) {
        this.viewGraph = viewGraph;
        this.systemMetaData = systemMetaData;
        allAtributes = new ArrayList<Atribute>();
        materializedViews = new HashMap<Integer, Table>();
        calcTableIndexes();
        for (Table dimRel : viewGraph.getRoot().getFKRelations()) {
            for (Table t : dimRel) {
                if (!t.isNullRelation()) {
                    allAtributes.add(t.getPrimaryKey().getAtribute());
                    for (Atribute a : t.getDescriptiveAtributes()) {
                        allAtributes.add(a);
                    }
                }
            }
        }
    }

    public ViewGraph getViewGraph() {
        return this.viewGraph;
    }

    /*
     * Build all ViewGeneMappers from all the views
     */
    private void calcTableIndexes() {
        int index = 0;
        for (ViewGene vg : viewGraph.getAllViews()) {
            vg.calcBitLength();
            vg.setTableIndex(index);
            index +=
                    vg.getBitLength();
        }

        for (Table dimRelation : viewGraph.getRoot().getFKRelations()) {
            for (Table relation : dimRelation) {
                relation.calcBitLength();
                relation.setTableIndex(index);
                index +=
                        relation.getBitLength();
            }

        }
    }

    public List<Atribute> getAllAtributes() {
        return allAtributes;
    }

    public void calculateTableVariants(IChromosome chromosome) {
        materializedViews.clear();
        int i = 0;
        for (ViewGene vg : viewGraph.getAllViews()) {
            vg.calculateTableVariant(chromosome);
            if (vg.isTableMaterialized) {
                materializedViews.put(i, vg);
            }
            i++;
        }
    }

    public SystemMetaData getSystemMetaData() {
        return systemMetaData;
    }

    public HashMap<Integer, Table> getMaterializedViews() {
        return materializedViews;
    }
}
